import { isUndefined, isNull, PagedList, PageParams, BackendServices } from "mmb";
import * as gsms_proxypb from "../grpc-client/util/gsms_proxy_pb";
import * as gsmspb from "../grpc-client/proxy/gsms_pb";

import {
  getGsmsProxySafely,
  getBgsGsmsProxyOpSafely,
  getMetadata,
  getOptionsOfLight,
  wrapperGrpcError,
} from "../grpc-client/grpcAdapter";

export interface SendVerifyCodeParams {
  phone: string;
  messageType: string;
}

export const sendVerifyCode = async ({phone, messageType}: SendVerifyCodeParams) => {
  const cl = getBgsGsmsProxyOpSafely();
  const req = new gsms_proxypb.SendVerifyCodeRequest();

  req.setPhone(phone);
  req.setMessageType(messageType);
   
  return new Promise((resolve, reject) => {
    cl.sendVerifyCode(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(true);
    });
  });
}

export interface VerifyCodeParams {
  phone: string;
  messageType: string;
  code: string
}

export const verifyCode = async ({phone, messageType, code}: VerifyCodeParams) => {
  const cl = getGsmsProxySafely();
  const req = new gsmspb.VerifyReq();
  
  req.setPhone(phone);
  req.setAppid(BackendServices.BGAPI)
  req.setMessagetype(messageType);
  req.setCode(code);
   
  return new Promise((resolve, reject) => {
    cl.codeVerify(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        console.log('err=>', err)
        reject(wrapperGrpcError(err.details));
        return;
      }
      if (!res.getVerifyresult()) {
        reject(wrapperGrpcError(res.getMessage()));
        return;
      }
      resolve(true);
    });
  });
}